import { useEffect, useState, useCallback } from "react";
import { Text, StyleSheet, ScrollView, Pressable, TouchableOpacity } from "react-native";
import { useSelector } from "react-redux";

import type { RootState } from "@/store";
import type { StateType } from "./type";

import getDeviceInfo from "@/utils/getDeviceInfo";
import { Module, AudioManage, LuminanceManage } from "@/utils/nativeModules";
import fso from "@/utils/FileOperate/operate";

import CustomIcon from "@/components/CustomIcon";
import globalMethods from "@/GlobalMethodProvider";

/** 设备信息 */
const DeviceInfo = () => {
  const storeRedux = useSelector((state: RootState) => state);

  const [state, _setState] = useState<StateType>({
    deviceInfo: null,
    appInfo: null,
    volume: 0,
    luminance: 0,
    isRoot: false
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  useEffect(() => {
    init();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /**
   * 获取信息
   * @param isTip 提示
   */
  const init = async (isTip = false) => {
    try {
      const _deviceInfo = await getDeviceInfo();
      setState("deviceInfo", _deviceInfo);

      const _appInfo = await Module.getAppInfo();
      if (_appInfo) {
        setState("appInfo", _appInfo);
      } else {
        console.log("APP信息获取失败");
      }

      /** 音量 */
      const volume = (await AudioManage.getCurrentVolume()) || 0;
      /** 亮度 */
      const luminance = (await LuminanceManage.getLuminance()) || 0;
      /** 是否 root */
      const isRoot = await Module.isRoot();
      setObjState({ volume, luminance, isRoot });

      if (isTip) {
        globalMethods.$success("刷新成功", 1000);
      }
    } catch (err) {
      console.log("err: ", err);
    }
  };

  // byte 转 MB
  const byteToGb = (num: number | undefined) => {
    if (num) {
      const ret = num / 1024 / 1024 / 1024;
      return ret.toFixed(2);
    } else {
      return 0;
    }
  };

  const RerfreshComp = (
    <TouchableOpacity style={styles.syncContaienr} onPress={() => init(true)}>
      <CustomIcon name="icon-Sync" size={36} />
    </TouchableOpacity>
  );

  const ComtentComp = state.deviceInfo ? (
    <Pressable>
      <Text style={styles.item}>
        系统: {state.deviceInfo.systemName} {state.deviceInfo.systemVersion} API {state.deviceInfo.APILevel}
      </Text>
      <Text style={styles.item}>资源文件目录: {fso.formatPath(fso.baseDir)}</Text>
      <Text style={styles.item}>userAgent: {state.deviceInfo.userAgent}</Text>
      <Text style={styles.item}>品牌: {state.deviceInfo.brand}</Text>
      <Text style={styles.item}>设备名称: {state.deviceInfo.deviceName}</Text>
      <Text style={styles.item}>MAC地址: {state.deviceInfo.mac}</Text>
      <Text style={styles.item}>Android ID: {state.deviceInfo.androidId}</Text>
      <Text style={styles.item}>IP: {state.deviceInfo.ip}</Text>
      {/* <Text style={styles.item}>应用首次安装日期: {dayjs(state.deviceInfo.firstInstallTime).format("YYYY-MM-DD HH:mm:ss")}</Text>
      <Text style={styles.item}>应用最近更新日期: {dayjs(state.deviceInfo.lastUpdateTime).format("YYYY-MM-DD HH:mm:ss")}</Text> */}
      <Text style={styles.item}>应用包名: {state.appInfo?.packageName}</Text>
      <Text style={styles.item}>应用构建日期: {state.appInfo?.buildDate}</Text>
      <Text style={styles.item}>应用版本号: {state.appInfo?.versionName}</Text>
      <Text style={styles.item}>是否ROOT: {state.isRoot ? "是" : "否"}</Text>
      <Text style={styles.item}>设备编号: {storeRedux.index.entryNetworkInfo?.code || ""}</Text>
      <Text style={styles.item}>亮度: {state?.luminance}%</Text>
      <Text style={styles.item}>音量: {state?.volume}%</Text>
      <Text style={styles.item}>
        已用存储: {byteToGb(state.deviceInfo.totalDiskCapacity - state.deviceInfo.freeDiskStorage)}GB
      </Text>
      <Text style={styles.item}>可用存储: {byteToGb(state.deviceInfo.freeDiskStorage)}GB</Text>
      <Text style={styles.item}>总存储: {byteToGb(state.deviceInfo.totalDiskCapacity)}GB</Text>
      <Text style={styles.item}>内存: {byteToGb(state.deviceInfo.totalMemory)}GB</Text>
      <Text style={styles.item}>电量: {Number(state.deviceInfo.batteryLevel * 100)}%</Text>
      <Text style={styles.item}>是否横屏: {state.deviceInfo.isLandscape ? "是" : "否"}</Text>
      <Text style={styles.item}>是否充电: {state.deviceInfo.isBatteryCharging ? "是" : "否"}</Text>
      <Text style={styles.item}>是否连接键盘: {state.deviceInfo.isKeyboardConnected ? "是" : "否"}</Text>
      <Text style={styles.item}>是否连接鼠标: {state.deviceInfo.isMouseConnected ? "是" : "否"}</Text>
    </Pressable>
  ) : (
    <Text>设备信息获取失败</Text>
  );

  return (
    <ScrollView>
      {ComtentComp}
      {RerfreshComp}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  item: {
    fontWeight: "bold",
    marginTop: 4,
    marginBottom: 4
  },
  syncContaienr: {
    position: "absolute",
    bottom: 20,
    right: 20,
    // backgroundColor: "red",
    borderRadius: 4,
    padding: 4
  }
});

export default DeviceInfo;
